<!--
 * @Author: your name
 * @Date: 2020-03-21 16:33:24
 * @LastEditTime: 2020-04-30 16:17:06
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \museweb\src\views\musePage\adminUser\changeAdminUser.vue
 -->
<template>
    <d2-container>
        <div>
            <el-form ref="detailForm" :model="detailForm" :rules="rules" label-width="80px">
                <el-form-item label="账号" prop="account">
                    <el-input placeholder="账号" v-model="detailForm.account" :disabled="!newadmin"></el-input>
                </el-form-item>
                <el-form-item v-if="newadmin" label="密码" prop="password">
                    <el-input placeholder="密码" v-model="detailForm.password"></el-input>
                </el-form-item>
                <el-form-item v-if="false" label="角色" prop="role">
                    <el-select style="width: 100%" multiple v-model="detailForm.role" placeholder="角色" @change="fnHandleChange">
                        <el-option
                                v-for="item in roleAry"
                                :key="item._id"
                                :label="item.name"
                                :value="item._id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="角色"  prop="role">
                  <el-checkbox-group v-model="detailForm.role" @change="fnHandleChange">
                    <el-checkbox v-for="item in roleAry" :key="item._id" :disabled="item.disabled" :label="item._id">{{item.name}}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item >
                    <el-button type="primary" @click="submitForm('detailForm')">确定</el-button>
                    <el-button @click="resetForm('detailForm')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
    </d2-container>
</template>

<script>
    import tableMixin from '../mixins/tableMixin'
    import { getOneAdmin,getRoles,changeOneAdmin } from '@/api/admin'
  export default {
    name: 'changeAdminUser',
    mixins: [tableMixin],
    data() {
      return {
        adminId:undefined,
        newadmin:true,
        oldDetailForm: {},
        detailForm: {
          account: '',
          password: '',
          role: [],
          store: []
        },
        roleAry: [],
        rules: {
          account: [
            { required: true, message: '请输入账号', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
          ],
          role: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ]
        },
        isShowStore: false,
        dialogDataVisible: false,
        tempShowData: []
      }
    },
    created () {
      this.getRoles()
    },
    methods: {
      // 获取列表数据
      async getRoles(value, type) {
        this.roleAry = (await getRoles()).data
        if(this.$route.query.id){
          this.newadmin = false
          this.adminId = this.$route.query.id
          getOneAdmin({id:this.adminId}).then((res)=>{
            this.detailForm = res.data
            const tempRole = []
            res.data.role.forEach(item => {
              tempRole.push(item._id)
            })
            this.detailForm.role = tempRole
            this.tempShowData = this.detailForm.store
            this.fnHandleChange(this.detailForm.role)
          })
        }
      },
      submitForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = {}
            data = this.detailForm
            data.id = this.adminId
            const tempStore = []
            this.tempShowData.forEach(item => {
              tempStore.push(item._id)
            })
            data.store = tempStore
            if(!this.newadmin) {
              delete data.password
            }
            changeOneAdmin(data).then((res)=>{
              this.$router.push({name: 'adminUserList'})
            })
          } else {
            return false;
          }
        });
      },
      resetForm () {
        this.detailForm = this.oldDetailForm
      },
      fnHandleChange(value) {
        // 5e95e8205fad040795c45168  root
        // 5ea5267ba24a2636ce353f66  店长
        // 5ea52684a24a2636ce353f6c  店员
         this.roleAry.forEach(item => {
            item['disabled'] = false
          })
        if(value.includes('5e95e8205fad040795c45168')) {
          this.roleAry.forEach(item => {
            if(['5ea5267ba24a2636ce353f66', '5ea52684a24a2636ce353f6c'].includes(item._id)) {
              item['disabled'] = true
            }
          })
        } else if(value.includes('5ea5267ba24a2636ce353f66')) {
          this.roleAry.forEach(item => {
            if(['5e95e8205fad040795c45168', '5ea52684a24a2636ce353f6c'].includes(item._id)) {
              item['disabled'] = true
            }
          })
        } else if(value.includes('5ea52684a24a2636ce353f6c')) {
          this.roleAry.forEach(item => {
            if(['5e95e8205fad040795c45168', '5ea5267ba24a2636ce353f66'].includes(item._id)) {
              item['disabled'] = true
            }
          })
        }
        const tempAry = value.filter(item => {
          return ['5ea5267ba24a2636ce353f66', '5ea52684a24a2636ce353f6c'].includes(item)
        })

        if(tempAry.length > 0) {
          this.isShowStore = true
        } else {
          this.isShowStore = false
        }
        
        this.$forceUpdate()
      },
      // 打开门店弹框
      fnOpenPopup () {
          this.dialogDataVisible = true
          this.getTableData()
      },
      fnClosePopup () {
        this.dialogDataVisible = false
      },
      // 获得门店列表
      async getTableData(value, type) {
        let params = {
          page: type === 'page'? (value ? value : this.paging.page) : this.paging.page,
          pageSize: type === 'pageSize'? (value ? value : this.paging.pageSize) : this.paging.pageSize
        }
        const { code, data: { total, currentPage, data, pageSize } } = await getStoreList(params)
        this.paging.total = total
        this.paging.pageSize = pageSize
        this.paging.page = currentPage
        this.tableData = data

        const showAry = this.tableData.filter(item => {
          for(let i = 0; i < this.tempShowData.length; i++) {
            if(item._id === this.tempShowData[i]._id) {
              return true
            }
          }
        })

        this.$nextTick(() => {
          showAry.forEach(item => {
            this.$refs.ref_table.toggleRowSelection(item, true)
          })
        })
      },
     // 弹框选择项编辑
      handleSelectionChangeByDialog(valueAry, value) {
        this.tempShowData = this.tempShowData.map(item => {
          return JSON.stringify(item)
        })
        if (this.tempShowData.indexOf(JSON.stringify(value)) > -1) {
          this.tempShowData.splice(this.tempShowData.indexOf(JSON.stringify(value)), 1)
        } else {
          this.tempShowData.push(JSON.stringify(value))
        }
        this.tempShowData = this.tempShowData.map(item => {
          return JSON.parse(item)
        })
      },
      deleteRow(row) {
        this.wrapConfirm(4).then(() => {
          this.tempShowData.forEach((item, index) => {
            if(item._id === row._id) {
              this.tempShowData.splice(index, 1)
            }
          })
        }).catch(() => {})
      }
    }
  }
</script>

<style scoped>
</style>
